package com.chengyi.serialport.demo.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbConstants
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbInterface
import android.hardware.usb.UsbManager
import android.os.Environment
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AlertDialog
import com.chengyi.serialboard.sdk.FaceOfflineController
import com.chengyi.serialport.demo.R
import com.chengyi.serialport.demo.databinding.ActivityFaceTestBinding
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.Toaster
import com.wyj.databinding.BaseViewModel
import com.wyj.utils.FileUtils
import java.io.File

class ActivityFaceTest : BaseActivity<ActivityFaceTestBinding, ActivityFaceTest.ViewModel>() {

    companion object {
        private const val testUserId = "ba9c56f1907d45da80b21132db5653f9"
        private const val TAG = "FaceTest"
    }

    private val mRegisterReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val userId = intent?.getStringExtra("userId")
            val filePath = intent?.getStringExtra("filePath")
            if (!userId.isNullOrBlank()) {
                Log.e(TAG, "注册成功，userId=${userId},人脸副本：${filePath}")
                Toaster.show("注册成功")
            }
        }
    }
    private val mSearchReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val userId = intent?.getStringExtra("userId")
            if (!userId.isNullOrBlank()) {
                val msg = "识别结果：${userId}"
                Log.e(TAG, msg)
                Toaster.show(msg)
            }
        }
    }
    private val mDeleteReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val userIds = intent?.getStringExtra("userIds")
            if (!userIds.isNullOrBlank()) {
                val msg = "删除成功，${userIds}"
                Log.e(TAG, msg)
                Toaster.show(msg)
            }
        }
    }
    private var cameraDevice: UsbDevice? = null
    override fun getLayoutRes(): Int = R.layout.activity_face_test
    override fun initViews() {
        initBar(binding.myTopBar)
        binding.btnRegister.setOnClickListener {
            onCameraSelect {
                val outDir = File(Environment.getExternalStorageDirectory(), "serialboardFace")
                val lock = File(outDir, "lock.txt")
                FileUtils.createNewFile(lock.absolutePath)
                FaceOfflineController.openRegisterActivity(this, testUserId, it, 0, outDir.absolutePath)
            }
        }
        binding.btnSearch.setOnClickListener {
            onCameraSelect {
                FaceOfflineController.openSearchActivity(this, it, 0)
            }
        }
        binding.btnDelete.setOnClickListener {
            FaceOfflineController.sendDeleteBroadcast(this, testUserId)
        }
        registerReceiver(mRegisterReceiver, IntentFilter(FaceOfflineController.FACE_OFFLINE_REGISTER_CALLBACK_ACTION))
        registerReceiver(mSearchReceiver, IntentFilter(FaceOfflineController.FACE_OFFLINE_SEARCH_CALLBACK_ACTION))
        registerReceiver(mDeleteReceiver, IntentFilter(FaceOfflineController.FACE_OFFLINE_DELETE_CALLBACK_ACTION))
        XXPermissions.with(this).permission(Permission.CAMERA, Permission.MANAGE_EXTERNAL_STORAGE).request { permissions, allGranted ->

        }
    }


    private fun onCameraSelect(callback: (UsbDevice) -> Unit) {
        val device = cameraDevice
        if (device != null) {
            callback(device)
        } else {
            val list = arrayListOf<UsbDevice>()
            val usbManager = getSystemService(Context.USB_SERVICE) as? UsbManager
            usbManager?.deviceList?.values?.forEach {
                if (isCameraDevice(it)) {
                    list.add(it)
                }
            }
            if (list.size == 1) {
                callback(list[0])
            } else if (list.size > 1) {
                val arrayString = list.map { it.productName ?: it.deviceName }.toTypedArray()
                showSelectionDialog(this, arrayString) { selectedItem, position ->
                    val device = list.getOrNull(position)
                    if (device != null) {
                        cameraDevice = device
                        callback(device)
                    }
                }
            } else {
                Toaster.show("未找到摄像头")
            }
        }
    }


    private fun isCameraDevice(usbDevice: UsbDevice): Boolean {
        val interfaceCount = usbDevice.interfaceCount
        // 遍历所有接口
        for (i in 0 until interfaceCount) {
            val usbInterface = usbDevice.getInterface(i)
            // 检查接口是否是一个摄像头接口
            if (isCameraInterface(usbInterface)) {
                return true
            }
        }
        // 未找到摄像头接口
        return false
    }

    private fun isCameraInterface(usbInterface: UsbInterface): Boolean {
        // 检查接口的端点数量和类型等信息，根据摄像头的常见配置进行判断
        val endpointCount = usbInterface.endpointCount
        // 这里是一个简单的示例，你可能需要更详细的逻辑来判断是否是摄像头接口
        return endpointCount > 0 && usbInterface.interfaceClass == UsbConstants.USB_CLASS_VIDEO
    }

    private fun showSelectionDialog(context: Context, arrayString: Array<String>, callback: (selectedItem: String, position: Int) -> Unit) {
        val dialogBuilder = AlertDialog.Builder(context)
        dialogBuilder.setTitle("请选择摄像头")
        // 设置选项列表
        dialogBuilder.setItems(arrayString) { dialog, which ->
            // 用户点击了哪个项目
            val selectedItem = arrayString[which]
            callback(selectedItem, which)
            dialog.dismiss()
        }
        // 设置取消按钮
        dialogBuilder.setNegativeButton("取消") { dialog, _ ->
            dialog.dismiss()
        }
        // 创建并显示对话框
        val dialog = dialogBuilder.create()
        dialog.show()
        setDialogWidth(dialog, context, 0.88f)
    }


    /**
     * 设置对话框宽度
     * @param dialog 对话框
     * @param context 上下文
     * @param widthPercentage 宽度比例（0.0 - 1.0）
     */
    private fun setDialogWidth(dialog: AlertDialog, context: Context, widthPercentage: Float) {
        val window = dialog.window ?: return
        // 获取屏幕宽度
        val displayMetrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        val screenWidth = displayMetrics.widthPixels
        // 计算目标宽度
        val targetWidth = (screenWidth * widthPercentage).toInt()
        // 设置对话框宽度
        window.setLayout(targetWidth, WindowManager.LayoutParams.WRAP_CONTENT)
    }

    override fun onDestroy(binding: ActivityFaceTestBinding?) {
        unregisterReceiver(mRegisterReceiver)
        unregisterReceiver(mSearchReceiver)
        unregisterReceiver(mDeleteReceiver)
    }

    class ViewModel : BaseViewModel() {

    }
}